package com.aabte.springdocopenapi.controller;

import com.aabte.springdocopenapi.entity.Person;
import com.aabte.springdocopenapi.service.PersonNotFoundException;
import com.aabte.springdocopenapi.service.PersonService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Collection;

@Slf4j
@RestController
@RequestMapping(value = "/api/test")
public class TestController {

    @Resource
    private PersonService personService;

    @GetMapping("/{id}")
    public Person findById(@PathVariable long id) {
        try {
            return personService.findById(id);
        } catch (PersonNotFoundException e) {
            log.error("findById failed. ", e);
            throw new PersonNotFoundApiException(e);
        }
    }

    @GetMapping
    public Collection<Person> findPersons() {
        return personService.findAll();
    }

    @PutMapping
    public Person updatePerson(@RequestBody final Person newPerson) {
        try {
            return personService.updatePerson(newPerson);
        } catch (PersonNotFoundException e) {
            log.error("updatePerson failed. ", e);
            throw new PersonNotFoundApiException(e);
        }
    }

    @PostMapping
    public Person addPerson(@RequestBody final Person newPerson) {
        return personService.addPerson(newPerson);
    }
}
